package com.toremo.frontline.services;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.dozer.DozerBeanMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.toremo.frontline.dto.ProjectDTO;
import com.toremo.frontline.model.Project;

@Service
public class ProjectServices {

	private EntityManager entityManager;
	private DozerBeanMapper beanMapper;

	@PersistenceContext
	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}
	
	@Autowired @Required
	public void setBeanMapper(DozerBeanMapper beanMapper) {
		this.beanMapper = beanMapper;
	}

	@Transactional
	public void create(ProjectDTO project) {
		if (project == null) {
			throw new IllegalArgumentException("Project cannot be null");
		}
		Project target = beanMapper.map(project, Project.class);
		// Prevent the ID and the version to be forget from the client side
		target.setId(null);
		target.setVersion(null);
		entityManager.persist(target);
	}

	public ProjectDTO find(long id) {
		Project result = entityManager.find(Project.class, id);
		if (result == null) {
			return null;
		} else {
			ProjectDTO response = beanMapper.map(result, ProjectDTO.class);
			return response;
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<ProjectDTO> find(String name, String description, Date startedFrom, Date startedTo) {
		Query q = new QueryBuilder()
				.add("select p from Project p")
				.when(name != null).filter("p.name like ?", "%" + name + "%")
				.when(description != null).filter("p.description like ?", "?" + description + "?")
				.build(entityManager);
		List<Project> projects = q.getResultList();
		List<ProjectDTO> result = new ArrayList<ProjectDTO>(projects.size());
		for (Project p: projects) {
			result.add(beanMapper.map(p, ProjectDTO.class));
		}
		return result;
	}
}
